package com.sdkdjn.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sdkdjn.pojo.AccessRecord;
import com.sdkdjn.pojo.Student;
import com.sdkdjn.service.IIEGService;
import com.sdkdjn.utils.FastDFSClient;
import com.sdkdjn.utils.IEGResult;
import com.sdkdjn.utils.MyStringUtils;
import com.sdkdjn.utils.PageBean;

@Controller
public class IEGController {

	@Value("${IMAGE_SERVER_URL}")
	private String IMAGE_SERVER_URL;

	@Autowired
	private IIEGService iEGService;

	@RequestMapping("/wechat/access_record/list")
	public String weChatAccessRecordList(@RequestParam(name = "time", defaultValue = "1") Integer time,
			@RequestParam(name = "buildingNumber", defaultValue = "0") Integer buildingNumber,
			@RequestParam(name = "state", defaultValue = "0") Integer state, HttpServletRequest request) {
		request.setAttribute("accessRecordList", iEGService.getAccessRecordList(time, buildingNumber, state));
		request.setAttribute("time", time);
		request.setAttribute("buildingNumber", buildingNumber);
		request.setAttribute("state", state);
		return "wechat_access_record";
	}

	@RequestMapping("/access_record_details/{id}")
	public String weChatAccessRecordList(@PathVariable Long id, HttpServletRequest request) {
		if (id != null) {
			request.setAttribute("accessRecord", iEGService.findAccessRecordById(id));
		}
		return "access_record_details";
	}

	@RequestMapping("/student/upload_picture/{id}")
	@ResponseBody
	public IEGResult editBookPicture(MultipartFile pictureFile, @PathVariable Long id) {
		try {
			if (id == null || pictureFile == null) {
				return IEGResult.iEGResultError("上传图片失败！");
			}
			// 把图片上传的图片服务器
			FastDFSClient fastDFSClient = new FastDFSClient("classpath:conf/client.conf");
			// 取文件扩展名
			String originalFilename = pictureFile.getOriginalFilename();
			String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
			// 得到一个图片的地址和文件名
			String url = fastDFSClient.uploadFile(pictureFile.getBytes(), extName);
			if (url == null) {
				return IEGResult.iEGResultError("上传图片失败！");
			}
			Student student = new Student();
			student.setId(id);
			student.setPictureUrl(url);
			iEGService.updateStudent(student);
			return IEGResult.iEGResultOK(url);
		} catch (Exception e) {
			e.printStackTrace();
			return IEGResult.iEGResultError("上传图片失败！");
		}
	}

	@RequestMapping("/student_access")
	@ResponseBody
	public IEGResult studentAccess(@RequestBody AccessRecord accessRecord) {
		try {
			byte[] pictureFileDecode = Base64.decodeBase64(accessRecord.getStringPic());
			// 把图片上传的图片服务器
			FastDFSClient fastDFSClient = new FastDFSClient("classpath:conf/client.conf");
			// 得到一个图片的地址和文件名
			String url = fastDFSClient.uploadFile(pictureFileDecode, "jpg");
			if (url != null) {
				accessRecord.setPictureUrl(url);
				iEGService.studentAccess(accessRecord);
				return IEGResult.iEGResultOK(IMAGE_SERVER_URL + url);
			}
			return IEGResult.iEGResultError("上传图片失败！");
		} catch (Exception e) {
			e.printStackTrace();
			return IEGResult.iEGResultError("上传图片失败！");
		}
	}

	@RequestMapping("/student/list")
	@ResponseBody
	public PageBean<Student> studentList(@RequestParam(name = "offset", defaultValue = "0") int offset,
			@RequestParam(name = "limit", defaultValue = "10") int limit,
			@RequestParam(name = "sort", defaultValue = "sort") String sort,
			@RequestParam(name = "order", defaultValue = "desc") String order, String search) {
		return iEGService.studentList(offset / limit + 1, limit, MyStringUtils.underscoreminName(sort), order, search);
	}

	@RequestMapping("/student/add")
	@ResponseBody
	public IEGResult addStudent(Student student, MultipartFile pictureFile) {
		try {
			// 把图片上传的图片服务器
			FastDFSClient fastDFSClient = new FastDFSClient("classpath:conf/client.conf");
			// 取文件扩展名
			String originalFilename = pictureFile.getOriginalFilename();
			String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
			// 得到一个图片的地址和文件名
			String url = fastDFSClient.uploadFile(pictureFile.getBytes(), extName);
			if (url != null) {
				student.setPictureUrl(url);
				return iEGService.addStudent(student);
			}
			return IEGResult.iEGResultError("上传照片失败！");
		} catch (Exception e) {
			e.printStackTrace();
			return IEGResult.iEGResultError("上传照片失败！");
		}
	}

	@RequestMapping("/student/update")
	@ResponseBody
	public IEGResult updateStudent(Student student) {
		return iEGService.updateStudent(student);

	}

	@RequestMapping("/student/delete")
	@ResponseBody
	public IEGResult deleteStudent(Long id) {
		return iEGService.deleteStudent(id);

	}

	@RequestMapping("/access_record/list")
	@ResponseBody
	public PageBean<AccessRecord> accessRecordList(@RequestParam(name = "offset", defaultValue = "0") int offset,
			@RequestParam(name = "limit", defaultValue = "10") int limit,
			@RequestParam(name = "sort", defaultValue = "access_time") String sort,
			@RequestParam(name = "order", defaultValue = "desc") String order, String search) {
		return iEGService.accessRecordList(offset / limit + 1, limit, MyStringUtils.underscoreminName(sort), order,
				search);
	}

	@RequestMapping("/login")
	public String managerLogin(String telephone, String password, HttpServletRequest request,
			HttpServletResponse response) {
		IEGResult result = iEGService.managerLogin(telephone, password);
		if (result.getStateCode() == IEGResult.OK) {
			request.getSession().setAttribute("loginManager", result.getData());
			request.getSession().setAttribute("imageServiceUrl", IMAGE_SERVER_URL);
			return "index";
		} else {
			return "login";
		}
	}

	@RequestMapping("/control")
	public void controlIEG(Integer state) {
		iEGService.controlIEG(state);
	}

	@RequestMapping("/student/find/{studentId}")
	@ResponseBody
	public IEGResult findStudentByStudentNumber(@PathVariable Long studentId) {
		return iEGService.findStudentByStudentId(studentId);
	}

	@RequestMapping("/access_record")
	public String accessRecordPage() {
		return "access_record";
	}

	@RequestMapping("/student")
	public String studentPage() {
		return "student";
	}
}
